<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="48">
          <a-col :span="12">
            <a-form-model-item label="物料大类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="provisionBroad">
              <a-select
                v-model="model.provisionBroad"
                :disabled="companNameFlag"
                placeholder="请选择物料大类"
                :showSearch="true"
                :allowClear="true"
                :filterOption="filterOption"
                @change="handleChange"
                :getPopupContainer="(triggerNode)=>{ return triggerNode.parentNode}"
              >
                <a-select-option v-for="item in provisionBroadList" :key="item.id" :value="item.id">{{ item.categoryName }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="物料小类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="provisionSmall">
              <a-select
                v-model="model.provisionSmall"
                :disabled="companNameFlag"
                placeholder="请选择物料小类"
                :showSearch="true"
                :allowClear="true"
                :filterOption="filterOption"
                @change="provisionSmallChange"
                :getPopupContainer="triggerNode => {return triggerNode.parentNode}"
              >
                <a-select-option v-for="item in provisionSmallList" :key="item.id" :value="item.id">{{ item.categoryName }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="warrantType != 5">
            <a-form-model-item label="物料编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialBillId">
              <a-input disabled v-model="model.materialBillId" placeholder="请输入物料编号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="物料名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialName">
              <select-material-input
                v-model="model.materialName"
                :multi="warrantType == 5"
                :disabled="companNameFlag"
                :materialFlag="true"
                :materialSmall="model.provisionSmall"
                @back="materialNameBack"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="warrantType != 5">
            <a-form-model-item label="规格型号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="specification">
              <a-input disabled v-model="model.specification" placeholder="请输入规格型号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="warrantType != 5">
            <a-form-model-item label="单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="unit">
              <j-dict-select-tag
                type="list"
                v-model="model.unit"
                placeholder="请选择单位"
                dictCode="unit_type"
                disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="warrantType != 5">
            <a-form-model-item label="品牌" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="brand">
              <a-input v-model="model.brand" placeholder="请输入品牌" disabled ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="warrantType != 5">
            <a-form-model-item label="供应商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="companName">
              <select-customer-input :disabled="companNameFlag" placeholder="请选择供应商" commercialType="2" v-model="model.companName"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="purchaseFlagTwo && warrantType != 5">
            <a-form-model-item :label="purchaseNumLabel" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseNum">
              <a-input-number
                disabled
                :min="0"
                v-model="model.purchaseNum"
                placeholder="请输入数量"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="purchaseFlag && warrantType != 5">
            <a-form-model-item label="累计已入库数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="warrantAmount">
              <a-input-number
                disabled
                :min="0"
                v-model="model.warrantAmount"
                placeholder="请输入累计已入库数量"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="warrantType != 5">
            <a-form-model-item :label="deliveryNumLabel" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deliveryNum">
              <a-input-number
                :disabled="formDisabled"
                @change="numberChange"
                :min="0"
                v-model="model.deliveryNum"
                placeholder="请输入数量"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="warrantType != 5">
            <a-form-model-item :label="returnNumLabel" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="returnNum">
              <a-input-number
                :disabled="formDisabled"
                @change="numberChange"
                :min="0"
                :max="returnMaxNum"
                v-model="model.returnNum"
                placeholder="请输入退回数量"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="warrantType != 5">
            <a-form-model-item :label="warrantNumLabel" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="warrantNum">
              <a-input-number disabled v-model="model.warrantNum" placeholder="请输入入库数量" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="warrantType != 5">
            <a-form-model-item label="存放仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="storehouseId">
              <a-select
                v-model="model.storehouseId"
                :disabled="formDisabled"
                placeholder="请输入存放仓库"
                :showSearch="true"
                :allowClear="true"
                :filterOption="filterOption"
                :getPopupContainer="triggerNode => {return triggerNode.parentNode}"
              >
                <a-select-option v-for="item in foldWarehouseList" :key="item.id" :value="item.id">{{ item.categoryName }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="warrantType != 5">
            <a-form-model-item label="生产日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="dateProduced">
              <!-- <j-date :disabled="formDisabled" placeholder="请选择生产日期" v-model="model.dateProduced"  style="width: 100%" /> -->
              <a-date-picker
                style="width: 100%"
                :disabled="formDisabled"
                placeholder="请选择生产日期"
                @change="handleDateChange"
                v-model="model.dateProduced"
                :disabled-date="disabledDate"
                format="YYYY-MM-DD"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="warrantType != 5">
            <a-form-model-item label="有效期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="periodValidity">
              <a-input-number
                :disabled="formDisabled"
                @change="periodValiditychange"
                :min="0"
                v-model="model.periodValidity"
                placeholder="请输入有效期"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="warrantType != 5">
            <a-form-model-item label="有效期单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="periodValidityUnit">
              <j-dict-select-tag :disabled="formDisabled" type="list" v-model="model.periodValidityUnit" placeholder="请选择有效期单位" dictCode="period_validity_unit"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if="warrantType != 5">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.remark" rows="4" placeholder="请输入备注"/>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import SelectProjectInput from '@/views/scy/components/SelectProjectInput'
  import SelectMaterialInput from '@/views/scy/components/SelectMaterialInput'
  import SelectCustomerInput from '@/views/scy/components/SelectCustomerInput'
  import moment from 'moment'
  export default {
    name: 'ErpPurchaseWarehouseWarrantDetailForm',
    components: {
      SelectProjectInput,
      SelectMaterialInput,
      SelectCustomerInput
    },
    props: {
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      storer: {
        type: String,
        default: ''
      },
      warrantType: {
        type: String,
        default: ''
      }
    },
    data () {
      return {
        materialDetail: [], // 物料名称数组
        flag: false,
        model: {},
        labelCol: {},
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        validatorRules: {
          provisionBroad: [
              { required: true, message: '请选择物料大类!', trigger: 'blur' }
          ],
          provisionSmall: [
              { required: true, message: '请选择物料小类!', trigger: 'blur' }
          ],
          materialName: [
              { required: true, message: '请选择物料名称!', trigger: 'change' }
          ],
          deliveryNum: [
              { required: true, message: '请输入数量!', trigger: 'blur', type: 'number' },
              { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正整数!' }
          ],
          returnNum: [
              { required: true, message: '请输入退回数量!', trigger: 'blur', type: 'number' },
              { pattern: /^[0-9]\d*$/, message: '请输入整数!' }
          ],
          warrantNum: [
            { required: true, message: '请输入入库数量!', trigger: 'blur', type: 'number' },
            { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正整数!' }
          ],
          storehouseId: [
              { required: true, message: '请选择存放仓库!', trigger: 'blur' }
          ],
          // dateProduced: [
          //     { required: true, message: '请选择生产日期!', trigger: 'change' }
          // ],
          periodValidity: [
              { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正整数!' }
          ],
          purchaseNum: [
              { required: true, message: '请输入数量!', trigger: 'blur', type: 'number' },
              { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正整数!' }
          ],
          warrantAmount: [
              { required: true, message: '请输入累计已入库数量!', trigger: 'blur', type: 'number' },
              { pattern: /^[0-9]\d*$/, message: '请输入整数!' }
          ]
        },
        url: {
          queryProvisionBroadList: '/api/erp/purchase/material/erpMaterialCategory/queryAllParent',
          queryProvisionSmallList: '/api/erp/purchase/material/erpMaterialCategory/queryChildrenByParentId',
          queryByStorehouseManager: '/api/erp/purchase/storehouse/erpStorehouseBase/queryByStorehouseManager'
        },
        provisionBroadList: [],
        provisionSmallList: [],
        foldWarehouseList: [],
        modelDateProduced: null,
        purchaseFlag: true,
        purchaseFlagTwo: true,
        companNameFlag: true,
        deliveryNumLabel: '',
        returnNumLabel: '',
        warrantNumLabel: '',
        purchaseNumLabel: ''
      }
    },
    computed: {
      formDisabled() {
        return this.disabled
      },
      returnMaxNum: function () {
        if (this.model.returnNum > this.model.deliveryNum) {
          this.$message.warning('退回数量不可超过送货数量')
        }
        if (this.model.deliveryNum) {
          return this.model.deliveryNum
        } else {
          return 0
        }
      }
    },
    watch: {
      storer: {
        handler (val) {
          if (val) {
            this.handleChangeFoldApplicant(val)
          }
        },
        immediate: true
      },
      warrantType: {
        handler (val) {
          if (val) {
            this.handleChangeWarrantType(val)
            this.getRule(val)
          }
        },
        immediate: true
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      // 修改必填
      getRule (val) {
        if (val && val == 5) {
          // 代表选择了其他 - 清除校验
          // this.$refs['form'].clearValidate('deliveryNum');
          // this.$refs['form'].clearValidate('returnNum');
          // this.$refs['form'].clearValidate('warrantNum');
          // this.$refs['form'].clearValidate('storehouseId');
          // this.$refs['form'].clearValidate('dateProduced');
          // this.$refs['form'].clearValidate('periodValidity');
          // this.$refs['form'].clearValidate('purchaseNum');
          // this.$refs['form'].clearValidate('warrantAmount');
        }
      },

      handleDateChange (mom, dateStr) {
        this.modelDateProduced = dateStr
      },
      disabledDate(current) {
        // Can not select days before today and today
        return current && current >= moment().endOf('day');
      },
      numberChange() {
        this.$refs['form'].clearValidate('warrantNum');
        if (this.model.returnNum && this.model.deliveryNum) {
          this.model.warrantNum = this.model.deliveryNum - this.model.returnNum
        } else {
          if (this.model.returnNum === 0) {
            this.model.warrantNum = this.model.deliveryNum
          } else {
            this.model.warrantNum = null
          }
        }
      },
      periodValiditychange(val) {
        if (val) {
          this.$set(this.validatorRules, 'periodValidityUnit', [
            { required: true, message: '请输入有效期单位!', trigger: 'blur' }
          ])
        } else {
          this.$set(this.validatorRules, 'periodValidityUnit', null)
        }
      },
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
        this.$refs['form'].clearValidate();
        this.findProvisionBroadList()
        this.model = Object.assign({}, record);
        this.provisionSmallList = []
        if (this.model.provisionBroad) {
          this.findProvisionSmallList(this.model.provisionBroad)
        }
        if (record.dateProduced) {
          this.model.dateProduced = moment(record.dateProduced, 'YYYY-MM-DD')
          this.modelDateProduced = record.dateProduced
        } else {
          this.modelDateProduced = null
        }
        this.visible = true;
      },
      handleChangeFoldApplicant(v, num = 0) {
        const that = this
        getAction(this.url.queryByStorehouseManager, { storehouseManager: v }).then((res) => {
          if (res.success) {
            that.foldWarehouseList = []
            res.result.forEach((res) => {
              that.foldWarehouseList.push({ 'id': res.id, 'categoryName': res.storehouseName })
            })
            let storehouseFlag = that.foldWarehouseList.some(item => item.id == this.model.storehouseId)
            if (!storehouseFlag) {
              this.$set(this.model, 'storehouseId', undefined)
            }
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      findProvisionBroadList() {
        const that = this
        that.provisionBroadList = []
        getAction(this.url.queryProvisionBroadList).then(res => {
          if (res.success) {
            res.result.forEach((res) => {
              that.provisionBroadList.push({ 'id': res.id, 'categoryName': res.categoryName })
            })
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      findProvisionSmallList(value) {
        const that = this
        const parentId = value
        getAction(this.url.queryProvisionSmallList, { parentId }).then(res => {
          if (res.success) {
            res.result.forEach((res) => {
              that.provisionSmallList.push({ 'id': res.id, 'categoryName': res.categoryName })
            })
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      handleChange(value) {
        this.provisionSmallChange()
        this.provisionSmallList = []
        this.$set(this.model, 'provisionSmall', undefined);
        this.$refs['form'].clearValidate('provisionSmall');
        if (value) {
          this.findProvisionSmallList(value)
        }
      },
      materialNameBack(data) {
        if (this.warrantType == 5) {
          this.materialDetail = data
          return false
        }
        const material = data[0]
        this.$set(this.model, 'materialBillId', material.materialBill)// 物料编码
        this.$set(this.model, 'brand', material.brand)// 品牌
        this.$set(this.model, 'specification', material.specification)// 规格型号
        this.$set(this.model, 'unit', material.unit)// 单位
        this.$set(this.model, 'deliveryNum', null)// 送货数量
        this.$set(this.model, 'returnNum', null)// 退回数量
        this.$set(this.model, 'warrantNum', null)// 入库数量
        this.$set(this.model, 'storehouseId', undefined)// 存放仓库
        this.$set(this.model, 'dateProduced', null)// 生产日期
        this.$set(this.model, 'periodValidity', null)// 有效期
        this.$set(this.model, 'periodValidityUnit', null)// 有效期单位
        this.$set(this.validatorRules, 'periodValidityUnit', null)// 清除有效期单位必填项
      },
      provisionSmallChange() {
        if (this.warrantType == 5) {
          this.$set(this.model, 'materialName', null)// 物料名称
        this.materialDetail = [] // 物料数组
          return false
        }
        
        this.$set(this.model, 'materialName', null)// 物料名称
        this.$set(this.model, 'materialBillId', null)// 物料编码
        this.$set(this.model, 'brand', null)// 品牌
        this.$set(this.model, 'specification', null)// 规格型号
        this.$set(this.model, 'unit', null)// 单位
        this.$set(this.model, 'deliveryNum', null)// 送货数量
        this.$set(this.model, 'returnNum', null)// 退回数量
        this.$set(this.model, 'warrantNum', null)// 入库数量
        this.$set(this.model, 'storehouseId', undefined)// 存放仓库
        this.$set(this.model, 'dateProduced', null)// 生产日期
        this.$set(this.model, 'periodValidity', null)// 有效期
        this.$set(this.model, 'periodValidityUnit', null)// 有效期单位
        this.$set(this.validatorRules, 'periodValidityUnit', null)// 清除有效期单位必填项
      },
      submitForm () {
        // 合同类 或 非合同类
        if (this.model.warrantNum && this.warrantType != 5) {
          if (this.warrantType == 1 || this.warrantType == 2) {
            let num = this.model.purchaseNum - this.model.warrantAmount
            if (num < this.model.warrantNum) {
              this.$message.warning('该类别本次入库数量（' + this.model.warrantNum + '）不能大于未入库数量（' + num + '）！');
              return
            }
          } else if (this.warrantType == 3) {
            if (this.model.purchaseNum < this.model.warrantNum) {
              this.$message.warning('该类别本次入库数量（' + this.model.warrantNum + '）不能大于领用数量（' + this.model.purchaseNum + '）！');
              return
            }
          }
        }
        const that = this;
        // 触发表单验证
        this.model.dateProduced = this.modelDateProduced
        this.$refs.form.validate(valid => {
          if (valid) {
            that.$emit('ok', this.model, this.flag, this.materialDetail);
          }
        })
      },
      handleChangeWarrantType(data) {
        if (data == 1 || data == 2) {
          this.companNameFlag = true
          this.purchaseFlag = true
          this.purchaseFlagTwo = true
          this.purchaseNumLabel = '采购数量'
          this.deliveryNumLabel = '本次送货数量'
          this.returnNumLabel = '本次退回数量'
          this.warrantNumLabel = '本次入库数量'
        } else if (data == 3) {
          this.companNameFlag = true
          this.purchaseFlag = false
          this.purchaseFlagTwo = true
          this.purchaseNumLabel = '领用数量'
          this.deliveryNumLabel = '领用返还数量'
          this.returnNumLabel = '退回数量'
          this.warrantNumLabel = '入库数量'
        } else {
          this.companNameFlag = false
          this.purchaseFlag = false
          this.purchaseFlagTwo = false
          this.deliveryNumLabel = '送货数量'
          this.returnNumLabel = '退回数量'
          this.warrantNumLabel = '入库数量'
        }
      }
    }
  }
</script>
